export default class NumberUtil {
  /**
   * 处理不规则数据。如-.   .  .00等不规则数据
   * @param {*} num
   * @returns
   */
  static dealIrregularNumber(num) {
    if ("null" == num) {
      num = "";
    }

    var str = "";
    num = num + "";
    if (num.startsWith("-.")) {
      str = num.replace("-.", "-0.");
    } else if (num.startsWith(".")) {
      str = num.replace(".", "0.");
    } else if (num.endsWith(".00")) {
      str = num.replace(".00", "");
    } else {
      str = num;
    }

    return str;
  }

  /**
   * 处理过大数据精度问题
   * @param {*} num
   * @param {*} index
   * @returns
   */
  static dealNumberPrecision(num, index) {
    //将字符串是数字的规则化
    num = NumberUtil.dealIrregularNumber(num);
    if (!num) return "-";
    //字符串不是数字直接返回
    else if (!NumberUtil.isNumber(num)) return num;
    //处理负数
    let prefixStr = "";
    if (num.indexOf("-") != -1) {
      prefixStr = "-";
      num = num.substring(1);
    }
    var param = {};
    var k = 10000,
      sizes = ["", "万", "亿", "万亿"],
      i;
    if (num < k) {
      if (num.indexOf(".") != -1) {
        param.value = (num / 1.0).toFixed(index);
        param.unit = "";
      } else {
        return num;
      }
    } else {
      i = Math.floor(Math.log(num) / Math.log(k));

      param.value = (num / Math.pow(k, i)).toFixed(index);
      param.unit = sizes[i];
    }
    return prefixStr + param.value + param.unit;
  }

  /**
   * 判断一个字符串是否为数字
   * @param {*} num
   * @returns
   */
  static isNumber(num) {
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
    var regNeg =
      /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(num) || regNeg.test(num)) {
      return true;
    } else {
      return false;
    }
  }

  /**
   * 处理负值显示特殊颜色
   * @param {*} num
   * @param {*} color 默认负值显示红色
   * @returns
   */
  static colorShowWithNumber(num) {
    if (num.indexOf("-") != -1 && num != "-") {
      return "red";
    } else {
      return "black";
    }
  }


  //回到顶部
  static scrollToTop = (scrollContainer, speed, step) => {
    // scrollContainer：要滚动的容器元素，可以是 window 或任意具有 scrollTop 属性的元素
    // speed：每次滚动的距离，即返回顶部的速度，默认为 10
    // step：每次滚动的时间间隔，单位为毫秒，默认为 10
    let scrollTop = scrollContainer.scrollTop
    const time = setInterval(() => {
      scrollTop -= speed
      if (scrollTop <= 0) {
        clearInterval(time)
        scrollContainer.scrollTop = 0
      } else {
        scrollContainer.scrollTop = scrollTop
      }
    }, step)
  }
}
